from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout, QHBoxLayout,
                             QPushButton, QRadioButton, QButtonGroup, QFrame,
                             QScrollArea, QTextEdit, QSizePolicy, QApplication)  # 添加 QApplication
from PyQt5.QtCore import Qt
import sys
from io import StringIO
from Data.Chinese import pdf
from Data import other_pdf
from Data.English import pdf_en


class OutputInterceptor(StringIO):
    def __init__(self, label):
        super().__init__()
        self.label = label
        self.original_stdout = sys.stdout

    def write(self, text):
        super().write(text)
        # 检查是否包含 ANSI 颜色代码
        if '\033[' in text:
            # 将 ANSI 颜色代码转换为 HTML
            text = text.replace('\033[93m', '<span style="color: #FFD700;">')
            text = text.replace('\033[31m', '<span style="color: #FF0000;">')
            text = text.replace('\033[0m', '</span>')
            if text.strip():  # 只有非空行才添加
                self.label.append(text.rstrip())
        else:
            # 非颜色文本使用绿色显示
            if text.strip():  # 只有非空行才添加
                text = f'<span style="color: #228B22;">{text}</span>'
                self.label.append(text.rstrip())

        # 自动滚动到底部
        self.label.verticalScrollBar().setValue(
            self.label.verticalScrollBar().maximum()
        )
        # 确保立即更新UI
        QApplication.processEvents()

    def flush(self):
        pass


class PdfUI(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def run_process(self):
        # 清空之前的信息
        self.info_label.clear()

        # 获取当前语言设置
        lang_combo = self.window().lang_combo
        is_chinese = lang_combo.currentText() == '中文'

        selected_button = self.button_group.checkedButton()
        selected_text = selected_button.text()

        # 设置输出重定向
        output_interceptor = OutputInterceptor(self.info_label)
        sys.stdout = output_interceptor

        try:
            # 更新信息显示
            if is_chinese:
                if selected_text == "SCG/CREF合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：中文")
                    pdf.pdf_collaboration(selected_text,None)
                if selected_text == "分册合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：中文")
                    other_pdf.volume_by_volume_collaboration(selected_text, is_chinese)
                if selected_text == "其它稿件":
                    print(f"运行处理，当前功能：{selected_text}")
                    other_pdf.volume_by_volume_collaboration(selected_text, is_chinese)
                if selected_text == "大本合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：中文")
                    pdf.pdf_collaboration(selected_text,None)
            else:
                if selected_text == "SCG/CREF合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：英文")
                    pdf_en.pdf_collaboration_en(selected_text)
                if selected_text == "分册合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：英文")
                    other_pdf.volume_by_volume_collaboration(selected_text, is_chinese)
                if selected_text == "其它稿件":
                    print(f"运行处理，当前功能：{selected_text}")
                    other_pdf.volume_by_volume_collaboration(selected_text, is_chinese)
                if selected_text == "大本合稿":
                    print(f"运行处理，当前功能：{selected_text}，当前语言：英文")
                    pdf_en.pdf_collaboration_en(selected_text)
        finally:
            # 恢复标准输出
            sys.stdout = output_interceptor.original_stdout

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(50, 30, 50, 50)

        # 创建标题
        title = QLabel('PDF合稿')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 10px 0 30px 0;')

        # 创建单选按钮组
        radio_container = QWidget()
        radio_layout = QHBoxLayout(radio_container)
        radio_layout.setAlignment(Qt.AlignCenter)

        self.button_group = QButtonGroup()

        # 创建四个单选按钮
        self.scg_cref_radio = QRadioButton("SCG/CREF合稿")
        self.volume_radio = QRadioButton("分册合稿")
        self.book_radio = QRadioButton("大本合稿")
        self.other_radio = QRadioButton("其它稿件")
        self.scg_cref_radio.setChecked(True)  # 默认选择SCG/CREF合稿

        # 设置单选按钮样式
        radio_style = """
            QRadioButton {
                font-size: 16px;
                color: #696969;
                padding: 5px;
                spacing: 10px;
                margin-top: 10px;
            }
            QRadioButton::indicator {
                width: 15px;
                height: 15px;
            }
        """

        # 应用样式并添加到按钮组和布局
        for radio in [self.scg_cref_radio, self.volume_radio, self.book_radio, self.other_radio]:
            radio.setStyleSheet(radio_style)
            self.button_group.addButton(radio)
            radio_layout.addWidget(radio)
            radio_layout.addSpacing(20)  # 按钮之间的间距

        # 创建运行按钮
        self.run_button = QPushButton('运行')
        self.run_button.setFixedSize(200, 40)
        self.run_button.setStyleSheet("""
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        self.run_button.clicked.connect(self.run_process)

        # 添加分割线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setStyleSheet("background-color: #A9A9A9;")
        line.setFixedHeight(2)

        # 创建信息显示区域
        self.info_label = QTextEdit()
        self.info_label.setReadOnly(True)
        self.info_label.setAcceptRichText(True)  # 允许富文本
        self.info_label.setStyleSheet("""
            QTextEdit {
                font-size: 14px;
                font-family: "Microsoft YaHei";
                margin-top: 10px;
                background-color: #F0FFF0;
                border: none;
            }
        """)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.info_label)
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #F0FFF0;
            }
            QScrollBar:vertical {
                width: 10px;
                background: #F0FFF0;
            }
            QScrollBar::handle:vertical {
                background: #A9A9A9;
                border-radius: 5px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        scroll_area.setMinimumHeight(300)  # 设置最小高度
        scroll_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 设置尺寸策略

        # 添加所有组件到主布局
        layout.addWidget(title)
        layout.addWidget(radio_container)
        layout.addSpacing(30)
        layout.addWidget(self.run_button, alignment=Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(line)
        layout.addWidget(scroll_area, 1)  # 添加拉伸因子1
        # layout.addStretch()  # 移除这行，让scroll_area自行扩展
